<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="聚合平台" name="onepane">
        <div class="cardBox" v-loading="loading">
          <el-form
            ref="smsConfigRef"
            :model="smsConfigForm.value"
            :rules="smsConfigRules"
            label-width="0px"
          >
            <el-descriptions title="短信配置信息" :column="3" border>
              <template slot="extra">
                <el-button
                  @click="doCancel"
                  v-if="Editing"
                  type="primary"
                  size="small"
                  >取消</el-button
                >
                <el-button
                  @click="doSaveSmsConfig"
                  v-if="Editing"
                  type="primary"
                  size="small"
                  >保存</el-button
                >
                <el-button
                  @click="Editing = !Editing"
                  v-if="!Editing"
                  type="primary"
                  size="small"
                  >编辑</el-button
                >
              </template>
              <el-descriptions-item label="平台">
                聚合平台
              </el-descriptions-item>
              <el-descriptions-item label="Key">
                {{ smsConfigData.value.key }}
              </el-descriptions-item>
              <el-descriptions-item label="Url">
                {{ smsConfigData.value.url }}
              </el-descriptions-item>

              <el-descriptions-item label="打开聚合平台" v-if="Editing">
                <el-switch
                  class="switch"
                  v-model="smsConfigForm.status"
                  :active-value="1"
                  :inactive-value="2"
                >
                </el-switch>
              </el-descriptions-item>
              <el-descriptions-item label="Key" v-if="Editing">
                <el-form-item prop="key">
                  <el-input
                    v-model="smsConfigForm.value.key"
                    placeholder="例如：10292664281fcd180e28b7c8212cdcd5"
                  />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="Url" v-if="Editing">
                <el-form-item prop="url">
                  <el-input
                    v-model="smsConfigForm.value.url"
                    placeholder="例如：http://v.juhe.cn/sms/send"
                  />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
          <el-card
            shadow="always"
            style="margin-top: 20px; box-shadow: 0 0 0 0"
          >
            <div slot="header">
              <el-button
                icon="el-icon-circle-plus-outline"
                type="primary"
                @click="goAddSmsTemplate"
                >添加模版</el-button
              >
            </div>
            <el-table :data="smsTemplateList" border stripe>
              <el-table-column prop="id" align="center" label="ID" />
              <el-table-column
                prop="template_id"
                align="center"
                label="模版ID"
              />
              <el-table-column
                prop="template_value"
                align="center"
                label="模版内容"
              />
              <el-table-column prop="type" align="center" label="类型">
                <template slot-scope="scope">
                  <div v-if="scope.row.type === 1">注册</div>
                  <div v-else-if="scope.row.type === 2">登录</div>
                  <div v-else-if="scope.row.type === 3">更换手机号</div>
                  <div v-else-if="scope.row.type === 4">设置支付密码</div>
                </template>
              </el-table-column>

              <el-table-column
                prop="created_at"
                align="center"
                label="创建时间"
              />
              <el-table-column
                prop="updated_at"
                align="center"
                label="更新时间"
              />
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="goEditSmsConfig(scope.row)"
                    >编辑</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
      <el-tab-pane label="腾讯云" name="twopane">
        <div class="cardBox">
          <el-form
            ref="smstencent"
            :model="smstencentForm"
            :rules="smstencentRules"
            label-width="0px"
          >
            <el-descriptions title="短信配置信息" :column="3" border>
              <template slot="extra">
                <el-button
                  @click="edittencener"
                  v-if="!tencentEditing"
                  type="primary"
                  size="small"
                  >编辑</el-button
                >
              </template>
              <el-descriptions-item label="平台"> 腾讯云 </el-descriptions-item>
              <el-descriptions-item label="sign_name">
                {{ smstencentData.value.sign_name }}
              </el-descriptions-item>
              <el-descriptions-item label="app_id">
                {{ smstencentData.value.app_id }}
              </el-descriptions-item>
              <el-descriptions-item label="region">
                {{ smstencentData.value.region }}
              </el-descriptions-item>
              <el-descriptions-item label="secret_id">
                {{ smstencentData.value.secret_id }}
              </el-descriptions-item>
              <el-descriptions-item label="secret_key">
                {{ smstencentData.value.secret_key }}
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
          <el-card
            shadow="always"
            style="margin-top: 20px; box-shadow: 0 0 0 0"
          >
            <div slot="header">
              <el-button
                icon="el-icon-circle-plus-outline"
                type="primary"
                @click="goAddSmstencentTemplate"
                >添加模版</el-button
              >
            </div>
            <el-table :data="smstencentList" border stripe>
              <el-table-column prop="id" align="center" label="ID" />
              <el-table-column
                prop="template_id"
                align="center"
                label="模版ID"
              />
              <el-table-column
                prop="template_value"
                align="center"
                label="模版内容"
              />
              <el-table-column prop="type" align="center" label="类型">
                <template slot-scope="scope">
                  <div v-if="scope.row.type === 1">注册</div>
                  <div v-else-if="scope.row.type === 2">登录</div>
                  <div v-else-if="scope.row.type === 3">更换手机号</div>
                  <div v-else-if="scope.row.type === 4">设置支付密码</div>
                </template>
              </el-table-column>
              <el-table-column
                prop="created_at"
                align="center"
                label="创建时间"
              />
              <el-table-column
                prop="updated_at"
                align="center"
                label="更新时间"
              />
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="goEditSmsConfig(scope.row)"
                    >编辑</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 腾讯云配置 -->
    <el-drawer
      :title="tencentitle"
      :visible.sync="drawer"
      @closed="closemansger"
      size="50%"
      :wrapperClosable="false"
    >
      <div style="padding: 20px">
        <el-form
          :model="smstencentForm.value"
          :rules="tencenRules"
          ref="reftencen"
        >
          <el-row>
            <el-form-item label="名称" label-width="80px" prop="sign_name">
              <el-input
                style="width: 240px"
                v-model="smstencentForm.value.sign_name"
                placeholder="请输入名称"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="region" label-width="80px" prop="region">
              <el-input
                style="width: 240px"
                v-model="smstencentForm.value.region"
                placeholder="请输入region"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="app_id" label-width="80px" prop="app_id">
              <el-input
                v-model="smstencentForm.value.app_id"
                placeholder="请输入app_id"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="secret_id" label-width="80px" prop="secret_id">
              <el-input
                v-model="smstencentForm.value.secret_id"
                placeholder="请输入secret_id"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item
              label="secret_key"
              label-width="80px"
              prop="secret_key"
            >
              <el-input
                v-model="smstencentForm.value.secret_key"
                placeholder="请输入secret_key"
              />
            </el-form-item>
          </el-row>

          <el-row>
            <el-form-item label="打开配置" label-width="80px" prop="status">
              <el-switch
                class="switch"
                v-model="smstencentForm.status"
                :active-value="1"
                :inactive-value="2"
              >
              </el-switch>
            </el-form-item>
          </el-row>

          <el-row style="margin-top: 100px">
            <div style="text-align: center">
              <el-button @click="closemansger()">取消</el-button>
              <el-button type="primary" @click="submitForms()">确认</el-button>
            </div>
          </el-row>
        </el-form>
      </div>
    </el-drawer>

    <!-- 聚合模版 -->
    <el-dialog
      :title="smsTemplateForm.template_id ? '编辑模板' : '添加模版'"
      :visible.sync="isShowDialog"
      @close="closeDialog"
      width="600px"
    >
      <el-row style="position: relative" v-loading="isShowLoading">
        <el-form
          ref="smsTemplateRefForm"
          :model="smsTemplateForm"
          :rules="smsTemplateRules"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="短信类型" prop="type">
                <el-select
                  v-model="smsTemplateForm.type"
                  placeholder="短信类型"
                  clearable
                >
                  <el-option
                    v-for="item in smsTypeList"
                    :key="item.type"
                    :label="item.value"
                    :value="item.type"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="模版ID" prop="template_id">
                <el-input
                  v-model="smsTemplateForm.template_id"
                  placeholder="请输入模版ID"
                />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="模版内容">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="smsTemplateForm.template_value"
                  placeholder="请输入模版内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <span slot="footer">
        <el-button :loading="isShowLoading" @click="isShowDialog = false"
          >取消</el-button
        >
        <el-button
          :loading="isShowLoading"
          type="primary"
          @click="doSaveSmsTemplate"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getsmsConfig,
  getsmsConfigsave,
  getsmslist,
  getsmssave,
} from "@/api/smsconfig/index";
import mix from "@/mixins/index";
export default {
  name: "SmsConfig",
  components: {},
  mixins: [mix],
  data() {
    const templateIdValidator = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("短信模版ID必填"));
      } else {
          const regexp = /^\d+$/;
        // const regexp = /^\d{6}$/;
        if (regexp.test(value)) {
          callback();
        } else {
          callback(new Error("短信模版ID为数字"));
        }
      }
    };
    return {
      tencentitle: "",
      drawer: false,
      statuscent: 1,
      isShowDialog: false,
      activeName: "onepane", // 默认激活的标签页是 "聚合"
      smsConfigData: {
        // 聚合短信配置数据
        value: {
          key: "",
          url: "",
        },
      },
      smstencentData: {
        // 腾讯短信配置数据
        name: "sms_config_tencent",
        value: {
          key: "",
          url: "",
        },
      },
      smsConfigForm: {
        name: "sms_config_key",
        status: 1,
        value: {
          key: "",
          url: "",
        },
      }, // 聚合保存短信配置表单
      smstencentForm: {
        name: "sms_config_tencent",
        status: 1,
        value: {
          app_id: "",
          secret_id: "",
          secret_key: "",
          region: "",
          sign_name: "",
        },
      }, //腾讯保存短信配置表单
      smsConfigRules: {
        url: [
          {
            required: true,
            type: "url",
            message: "请输入正确的短信请求地址",
            trigger: "blur",
          },
        ],
        key: [{ required: true, message: "短信请求key必填", trigger: "blur" }],
      },
      tencenRules: {},
      smstencentRules: {},
      // 短信模版配置表单
      smsTemplateForm: {
        type: "",
        template_id: "",
        template_value: "",
      },
      smsTemplateRules: {
        type: [{ required: true, message: "短信类型必填", trigger: "blur" }],
        template_id: [{ validator: templateIdValidator, trigger: "blur" }],
      },
      smsTypeList: [
        {
          type: 1,
          value: "注册",
        },
        {
          type: 2,
          value: "登录",
        },
        {
          type: 3,
          value: "更换手机号",
        },
        {
          type: 4,
          value: "设置支付密码",
        },
      ],
      smsTemplateList: [],
      smstencentList: [],
      smslistdata: {
        page: 1,
        page_size: 10,
        options_name: "",
      },
      loading: true,
      Editing: false,
      tencentEditing: false,
      isShowLoading: false,
    };
  },
  created() {
    this.getSms();
    this.getSmsTemplateConfig();
  },
  methods: {
    // 标签页点击事件
    handleTabClick(tab) {
      this.activeName = tab.name;
      if (tab.name == "twopane") {
        this.getSmstengcent();
        this.getSmstengxunyung();
      } else {
        this.getSms();
        this.getSmsTemplateConfig();
      }
    },
    // 获取聚合短信配置
    getSms() {
      this.loading = false;
      getsmsConfig({ name: "sms_config_key" }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          if (res.data && res.data.length==0) {
          }else{
            this.smsConfigForm.status = res.data.status;
            this.smsConfigData = res.data;
          }
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取腾讯短信配置
    async getSmstengcent() {
      this.loading = true;
      const res = await getsmsConfig({ name: "sms_config_tencent" });
      const { code, data, msg } = res;
      this.loading = false;
      if (code === 200) {
        if (data && data.length==0) {
        }else{
          this.smstencentData = data;
        }
      } else {
        this.$message.error(msg);
      }
    },
    // 保存聚合短信配置
    doSaveSmsConfig() {
      this.$refs.smsConfigRef.validate(async (valid, err) => {
        if (valid) {
          this.smsConfigForm.id = this.smsConfigData.id;
          let aar = JSON.stringify(this.smsConfigForm.value);
          this.smsConfigForm.value = aar;
          const res = await getsmsConfigsave(this.smsConfigForm);
          const { code, msg } = res;
          if (code === 200) {
            this.$message.success("保存短信配置成功！！！");
            // 更新数据
            this.getSms();
            this.Editing = false;
            (this.smsConfigForm = {
              name: "sms_config_key",
              value: {
                key: "",
                url: "",
              },
            }),
              (this.smsConfigData = {
                value: {
                  key: "",
                  url: "",
                },
              });
          } else {
            this.$message.error(msg);
            this.smsConfigData = {
              value: {
                key: "",
                url: "",
              },
            };
            this.smsConfigForm = {
              name: "sms_config_key",
              value: {
                key: "",
                url: "",
              },
            };
          }
        } else {
        }
      });
    },
    //编辑腾讯云短信配置
    edittencener() {
      this.tencentitle = "编辑短信配置";
      this.drawer = true;
      if (this.smstencentData) {
        this.smstencentForm.value = this.smstencentData.value;
        this.smstencentForm.status = this.smstencentData.status;
      } else {
        this.smstencentForm = {
          name: "sms_config_tencent",
          status: 2,
          value: {
            app_id: "",
            secret_id: "",
            secret_key: "",
            region: "",
            sign_name: "",
          },
        };
      }
    },
    //保存腾讯短信配置
    submitForms() {
      this.$refs.reftencen.validate(async (valid, err) => {
        if (valid) {
          let aar = JSON.stringify(this.smstencentForm.value);
          this.smstencentForm.value = aar;
          this.smstencentForm.id = this.smstencentData.id;
          getsmsConfigsave(this.smstencentForm).then((res) => {
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.getSmstengcent();
              this.getSmstengxunyung();
              this.closemansger();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
        }
      });
    },

    // 取消短信配置保存
    doCancel() {
      this.$refs.smsConfigRef.resetFields();
      this.Editing = false;
    },
    //腾讯取消短信配置保存
    tencentdoCancel() {
      this.$refs.smstencent.resetFields();
      this.tencentEditing = false;
    },
    // 获取聚合短信模版配置
    async getSmsTemplateConfig() {
      this.smslistdata.options_name = "sms_config_key";
      const res = await getsmslist(this.smslistdata);
      const { code, data, msg } = res;
      if (code === 200) {
        this.paginationObj.total = data.total;
        this.smsTemplateList = data.list;
      } else {
        this.$message.error(msg);
      }
    },
    //腾讯云短信模版配置
    async getSmstengxunyung() {
      this.smslistdata.options_name = "sms_config_tencent";
      const res = await getsmslist(this.smslistdata);
      const { code, data, msg } = res;
      if (code === 200) {
        this.paginationObj.total = data.total;
        this.smstencentList = data.list;
      } else {
        this.$message.error(msg);
      }
    },

    handleSizeChange(val) {
      // console.log(`每页${val}条`)
      this.paginationObj.limit = val;
      this.getSmsTemplateConfig();
    },
    handleCurrentChange(val) {
      // console.log(`当前第${val}页`)
      this.paginationObj.start = val;
      this.getSmsTemplateConfig();
    },
    // 去编辑短信模版配置
    goEditSmsConfig(row) {
      this.isShowDialog = true;
      this.smsTemplateForm = row;
      delete this.smsTemplateForm.created_at;
      delete this.smsTemplateForm.updated_at;
    },
    // 去编辑腾讯短信模版配置
    goEditSmstencent(id) {
      // this.isShowDialog = true;
      // const item = this.smsTemplateList.find((item) => item.id === id);
      // if (item) {
      //   this.$set(this.smsTemplateForm, "type", item.type);
      //   this.$set(this.smsTemplateForm, "template_id", item.template_id);
      //   this.$set(this.smsTemplateForm, "template_value", item.template_value);
      // }
    },
    // 去添加聚合短信模版
    goAddSmsTemplate() {
      this.isShowDialog = true;
    },
    //去添加腾讯短信模版
    goAddSmstencentTemplate() {
      this.isShowDialog = true;
    },

    // 保存短信模版配置
    doSaveSmsTemplate() {
      this.$refs.smsTemplateRefForm.validate(async (valid) => {
        if (valid) {
          if (this.activeName == "onepane") {
            //聚合
            this.smsTemplateForm.options_name = "sms_config_key";
            this.isShowLoading = true;
            const res = await getsmssave(this.smsTemplateForm);
            const { code, msg } = res;
            this.isShowLoading = false;
            if (code === 200) {
              // 关闭对话框
              this.isShowDialog = false;
              // 重置表单
              this.smsTemplateForm = this.$options.data().smsTemplateForm;
              // 重新获取数据
              this.getSmsTemplateConfig();
              this.$messages.success(msg);
            } else {
              this.$message.error(msg);
            }
          } else {
            this.smsTemplateForm.options_name = "sms_config_tencent";
            this.isShowLoading = true;
            const res = await getsmssave(this.smsTemplateForm);
            const { code, msg } = res;
            this.isShowLoading = false;
            if (code === 200) {
              // 关闭对话框
              this.isShowDialog = false;
              // 重置表单
              this.smsTemplateForm = this.$options.data().smsTemplateForm;
              // 重新获取数据
              this.getSmsTemplateConfig();
              this.$messages.success(msg);
            } else {
              this.$message.error(msg);
            }
          }
        } else {
          this.$message.warning("请注意表单验证！！！");
        }
      });
    },
    closemansger() {
      this.drawer = false;
      this.smstencentForm = {
        name: "sms_config_tencent",
        value: {
          app_id: "",
          secret_id: "",
          secret_key: "",
          region: "",
          sign_name: "",
        },
      };
    },

    closeDialog() {
      this.smsTemplateForm = {
        type: "",
        template_id: "",
        template_value: "",
      };
    },
  },
};
</script>
<style lang="scss" >
.app-container {
  /*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
  .el-drawer__body {
    overflow: auto;
  }

  /*2.隐藏滚动条，太丑了*/
  .el-drawer__container ::-webkit-scrollbar {
    display: none;
  }

  .el-drawer__header {
    background-color: #409eff;
    color: #ffffff;
    padding: 10px 20px;
    margin-bottom: 10px;
  }
}
</style>
<style lang="scss" scoped>
.switch {
  margin-right: 20px;
}
.margin-10 {
  margin: 10px;

  .info_text {
    font-weight: 700;
  }
}
</style>
